package com.neuedu.boot.framework;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.neuedu.boot.utils.JWTUtils;
import com.neuedu.boot.utils.ResUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 项目：      springboot
 * 类名:       LoginInterceptor
 * 创建时间：  2024/4/3 10：56
 * 描述 :
 * 作者 :     张金山
 * QQ :     314649444
 * Site:      https://jshand.gitee.io
 */
@Component
public class LoginInterceptor  implements HandlerInterceptor {

    @Autowired
    ObjectMapper objectMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String method = request.getMethod();
        System.out.println("method = " + method);
        if(method.equals("OPTIONS")){
            response.setStatus(200);
            return false ;
        }

        String token = request.getHeader("Authentication");
        boolean success = false;
        String msg = null;
        //token 认证
        if(!StringUtils.hasText(token) ){
            msg = "token不能为空";
        }

        if(StringUtils.isEmpty(msg)){
            DecodedJWT decode = JWTUtils.decode(token);
            if(decode ==null){
                msg = "Token无效";
            }
        }

        if(StringUtils.isEmpty(msg)){  //没有错误消息  ok
            return true;
        }else{
            //响应错误信息给客户端
            ResUtils.writeJSON(response,Res.failed(403,msg));
            return false;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
